/**
 * calculator
 *
 * @author : tzy
 * @Date : 2021-03-16
 * @Description:
 **/

package com.tang.calculator.functions;

import com.tang.calculator.context.CalculateContext;
import com.tang.calculator.symbols.ValueSymbol;
import com.tang.calculator.symbols.ValueSymbolFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.math.BigDecimal;
import java.util.Stack;

@Component
public class SumFunction extends AbstractFunction {

    @Autowired
    ValueSymbolFactory valueSymbolFactory;

    @Override
    public void operate(CalculateContext context) {
        super.operate(context);
    }

    @Override
    public String getFunctionName() {
        return "sum";
    }

    @Override
    public void run(CalculateContext context, ValueSymbol... args) {
        Stack<ValueSymbol> valueStack = context.getValueStack();
        BigDecimal res = new BigDecimal(0);

        ValueSymbol value = valueSymbolFactory.create(res.toString());
        for (int i = 0; i < args.length; i++) {
            if (args[i] instanceof ValueSymbol) {
                ValueSymbol valueSymbol = (ValueSymbol) args[i];
                res = value.getValue().add(valueSymbol.getValue());
                value = valueSymbolFactory.create(res.toString());
            }
        }

        ValueSymbol valueSymbol = valueSymbolFactory.create(res.toString());
        valueStack.push(valueSymbol);
    }
}
